import axios from 'axios'

const todo = {
  namespaced: true,
  state: { list: [], logo: 'all' },
  actions: {
    //获取列表
    async geList (context) {
      const res = await axios({
        method: 'GET',
        url: 'http://localhost:3000/todo'
      })
      context.commit('getTodoList', res.data)
    },

    //添加新的项 未完
    async addList (context, payload) {
      // console.log(payload)
      await axios({
        method: 'POST',
        url: 'http://localhost:3000/todo/',
        data: payload,
      })
      context.commit('pushTodoList', payload)
    },

    // //删除服务端单选项
    async delfn (state, id) {
      await axios({
        method: 'DELETE',
        url: 'http://localhost:3000/todo/' + id,
      })
      state.commit('delFnitem', id)
    },
    // 修改服务器中单项选中状态
    async changeCheckedStatus (state, id) {
      console.log(id)
      let status = state.state.list.find(item => item.id === id)
      status = !status.isDone
      console.log(status)
      await axios({
        method: 'PATCH',
        url: 'http://localhost:3000/todo/' + id,
        data: { isDone: status, }
      })
      state.commit('changIsdoneStatus', id)
    },
    changeServeStatus (state, status) {
      console.log(status)
      // 修改服务全选项 待完善
      state.commit('changeAllchecked', status)
    }
  },
  mutations: {
    //获取列表更新本地数据列表
    getTodoList (state, payload) {
      // const a = payload.filter(item => { item.id === 30 })
      // console.log(a)
      state.list = payload
    },
    //添加本地数据
    pushTodoList (state, payload) {
      const newitem = {}
      newitem.name = payload.name
      newitem.isDone = payload.isDone
      const num = state.list.length - 1
      const id = state.list[num].id + 1
      newitem.id = id
      state.list.push(newitem)
    },
    //删除本地单选项
    delFnitem (state, id) {
      state.list = state.list.filter((item) => item.id !== id)
    },
    //修改本地数据选中状态以便全选 多选联动
    changIsdoneStatus (state, id) {
      const changitemstatus = state.list.find(item => item.id === id)
      changitemstatus.isDone = !changitemstatus.isDone
    },
    changeAllchecked (state, status) {
      state.list.forEach(item => {item.isDone = status})
    },
    //三选 全部 已完成 进行中
    threeCheckFn (state, logo) {
      // console.log(logo)
      state.logo = logo
    },
    //清除已完成 剩下未完成的覆盖源数据
    clearCompletedFn (state) {
      state.list = state.list.filter(item => !item.isDone)
    }
  },
  getters: {
    // 剩余 待完成数量
    remain (state) {
      return state.list.filter(item => !item.isDone).length
    },
    // 三选一
    threeCheckOne (state) {
      if (state.logo === 'running') {
        return state.list.filter(item => !item.isDone)
      } else if (state.logo === 'completed') {
        return state.list.filter(item => item.isDone)
      } else {
        return state.list
      }
    }
  }
}
export default todo